/*
    Copyright 2009 Barnet Wagman

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package ot;

import java.util.*;
import java.io.*;

/**
 *
 * @author Barnet Wagman
 */
public class UtilOt {

        /** Loads list of params into a hash table.  Each string in <tt>argv</tt>
         *  must have the format
         *  <blockquote>
         *      &lt;param name&gt;=&lt;param value&gt;
         *  </blockquote>
         *  The hash table has 'param name's as keys and 'param values' as
         *  values.
         * @param argv
         * @return
         */
    public static HashMap<String,String> paramValuesToHt(String[] argv) {

        HashMap<String,String> ht = new HashMap<String, String>();

        for ( String arg : argv ) {
            String[] a = arg.split("=");
            if ( a.length != 2 )
                throw new RuntimeException("UtilOt.paramValuesToHt: " +
                                "Bad param=" + arg);
            ht.put(a[0],a[1]);
        }
        return(ht);
    }

        /** Loads a param file into a hash map. The file should contain
         *  one param per line format
         *  <blockquote>
         *      &lt;param name&gt;=&lt;param value&gt;
         *  </blockquote>
         *  Lines starting with '#' are considered comments and are ignored.
         *
         * @param paramFile
         * @return
         */
    public static HashMap<String,String> paramValuesToHt(File paramFile)
        throws IOException {

        FileReader fr = null;
        BufferedReader r = null;
        try {
            if ( !paramFile.exists() ) throw new RuntimeException("Param file " +
                        paramFile.getPath() + " does not exist.");
            if ( paramFile.isDirectory() ) throw new RuntimeException(paramFile.getPath() +
                        " is a directory, not a file.");

            fr = new FileReader(paramFile);
            r = new BufferedReader(fr);

            List<String> args = new ArrayList<String>();

            String line = "";
            NEXT: while ( (line = r.readLine()) != null ) {
                String s = line.trim();
                if ( s.startsWith("#") ) continue NEXT;
                else args.add(s);
            }
            return( paramValuesToHt( args.toArray(new String [args.size()]) ) );
        }
        finally {
           if ( fr != null ) fr.close();
           if ( r == null ) r.close();
        }
    }
}
